module uart_rx(
				//input 			
				clk,
				rxd,
				nrst,
				baud_set,
				//output
		 		error,
				rdc,
			 	data
				);
input	clk,	rxd,	nrst,baud_set;
output	error,rdc;
reg 	error,	rdc;
output 	[7:0]data; 
wire	[7:0]data;


reg[7:0] 		data0,data1;
reg	[3:0]		s;
reg	[11:0]		cnt;

wire[11:0]		baud;
wire[11:0]		baud_half;
	
parameter		BAUD_115200 = 12'd8, 	//baud rate 115200//1Mhz
				BAUD_19200 = 12'd51,  //baud rate 19200	
				BAUD_9600  = 12'd103;  // baud rate 9600

		


				//BAUD_115200 = 12'd433, 	//baud rate 115200//50Mhz
				//BAUD_19200 = 12'd2602;  //baud rate 19200


assign data = data1;
assign baud_half = {1'b0,baud[11:1]}; 	//half time 
assign baud = baud_set ? BAUD_9600 : BAUD_19200;

always@(posedge clk or negedge nrst)
if(!nrst)
	begin 
	data1<=8'h00;rdc<=0;s<=0;cnt <= 0;
	data0<=8'h00;error<=0;
	end
else 
	begin
	case(s)
	0:if(rxd==1)begin s<=1;cnt <= 0; rdc <= 1'b0; end
	1:if(rxd==0)begin s<=2;cnt <= cnt + 1'b1;end
	2:if(cnt == baud_half)
		begin 
			if(rxd==0)
				begin s<=3;cnt <= 0;error<=0;end 
			else 
				begin s<=1;cnt <= 0;end  
		end 
		else cnt <= cnt + 1'b1;
	3:if(cnt == baud) begin data0[0]<=rxd;s<=4;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	4:if(cnt == baud) begin data0[1]<=rxd;s<=5;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	5:if(cnt == baud) begin data0[2]<=rxd;s<=6;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	6:if(cnt == baud) begin data0[3]<=rxd;s<=7;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	7:if(cnt == baud) begin data0[4]<=rxd;s<=8;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	8:if(cnt == baud) begin data0[5]<=rxd;s<=9;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	9:if(cnt == baud) begin data0[6]<=rxd;s<=10;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	10:if(cnt == baud) begin data0[7]<=rxd;s<=11;cnt <= 0;end
	else cnt <= cnt + 1'b1;
	11:if(cnt == baud) 
		if(rxd==1) begin data1<=data0;s<=0;cnt <= 0;rdc<=1;error<=0;end
		else begin s<=0;cnt <= 0;error<=1;end
	   else cnt <= cnt + 1'b1;
	default:begin s<=0;cnt <= 0;end
	endcase
end
endmodule 
